import {Injectable} from '@angular/core';
import {Subscription} from "rxjs/Subscription";
import {BehaviorSubject} from "rxjs/BehaviorSubject";
import {HttpService} from "app/core/http/http.service";
import {ToolsService} from "app/shared/service/tools/tools.service";
import * as API from "@api/index";
import {Observable} from "rxjs/Observable";
import {
  CommonPageVo, MatchIpSignTeamResp, MatchSignFieldResp, MultilayerScoreVO, MultilayerScoreVOAlone,
  SNSResult
} from "@interface/index";



@Injectable()
export class MatchService {

  subscription: Subscription = new Subscription();
  public eventsDetails: any;
  public eventAnnounce: any;
  public eventRule: any;
  public detailHeader: any;
  public event_recoms: any;
  public isFilter = false;
  public saveSelected = {
    typeActive: 0,
    statusActive: 0,
    citySelect: '全国',
    recomName: '全部',
    matchIpRecomId: null,
    statusList: '3,4,5,6,7,8',
    formats: null,
  };
  public backUp = {
    typeActive: 0,
    statusActive: 0,
    citySelect: '全国',
    recomName: '全部',
    matchIpRecomId: null,
    statusList: '3,4,5,6,7,8',
    formats: null
  };
  public filterParam = {
    page: 1,
    rows: 15,
    matchIpRecomId: null,
    formats: null,
    statusList: '3,4,5,6,7,8',
    cityId: null,
  };
  public currentCity = {
    provinceId: null,
    cityId: null,
    provinceName: '全国',
    cityName: ''
  };
  public competitionStore = { // 赛事相关对象 @author ouyqx-691
    competitionType: null, // 赛事类型 0:个人，1:团体
    scheduleType: null,  // 赛程类型 24005:淘汰赛 24007:积分赛
    matchType: 0, // 赛事类型 足球3001
    joinRequire: 0, // 参赛者要求 (羽毛球（个人）20005，羽毛球（双人）20006 ...）
    joinRequireArr: [20006, 20008, 20010], // 双人参赛要求code数组(羽毛球，网球，乒乓球）
    behalfSmallScore: 0, // 是否可以录入小比分
    cupCodeArr: [24011, 24017] // 可用于杯赛的code
  };
  public _swiper: BehaviorSubject<any> = new BehaviorSubject<any>([]);
  public eventSwiper: any;

  constructor(public httpService: HttpService,
              public toolsService: ToolsService) {
  }

  // 筛选条件
  getMatchFilter() {
    const url = API.COMPETITIONS_FILTER + ``;
    return this.httpService.get(url).map((res) => res.json());
  }

  // 赛事
  getSwiper(page: number = 1, rows: number = 5) {
    const url = API.AD_LIST_URL + `?adsType=banner&showPosition=43&page=${page}&rows=${rows}`;
    return this.httpService.get(url).map((res) => res.json());
  }

  // 根据筛选条件获取赛事列表
  getFilterList(obj) {
    const url = API.COMPETITIONS_FILTER_LIST + '?' + this.toolsService.param(obj);
    return this.httpService.get(url).map((res) => res.json());
  }

  // 赛事
  getMatchs(page: number = 1, rows: number = 15) {
    const url = API.PERSON_EVENTS + `?statusList=3,4,5,6,7,8&page=${page}&rows=${rows}`;
    return this.httpService.get(url).map((res) => res.json());
  }

  // 赛事公告
  getAnnounce(obj) {
    const url = API.PERSON_EVENTS_ANNOUNCE + '?matchId=' + obj + '&rows=3';
    return this.httpService.get(url).map((res) => res.json());
  }

  // 赛事章程
  getRule(obj) {
    const url = API.PERSON_EVENTS_RULE + '?matchId=' + obj;
    return this.httpService.get(url).map((res) => res.json());
  }

  // 赛事详情
  getDetail(obj) {
    const url = API.PERSON_EVENTS_DETAIL_DETAIL + '?matchId=' + obj;
    return this.httpService.get(url).map((res) => res.json());
  }

  // 赛事详情头部
  getDetailHeader(obj) {
    const url = API.PERSON_EVENTS_DETAIL_HEADER + '?matchId=' + obj;
    return this.httpService.get(url).map((res) => res.json());
  }

  // 赛事详情头部
  getEventDetail(obj) {
    return new Promise(resolve => {
      this.getDetailHeader(obj).subscribe(res => {
        const object = res;
        if (object.result === 0 && object.data) {
          this.detailHeader = object.data;
        }
        resolve(this.detailHeader);
      });
    });
  }

  // 赛事详情
  getDetailDetail(obj) {
    return new Promise(resolve => {
      this.getDetail(obj).subscribe(res => {
        const object = res;
        if (object.result === 0 && object.data) {
          this.eventsDetails = object.data;
        } else {
          this.eventsDetails = '无';
        }
        resolve(this.eventsDetails);
      });
    });
  }

  // 赛事公告
  getAnnounces(obj) {
    return new Promise(resolve => {
      this.getAnnounce(obj).subscribe(res => {
        if (res.result === 0 && res.data.list.length > 0) {
          this.eventAnnounce = res.data.list;
        } else {
          this.eventAnnounce = '无';
        }
        resolve(this.eventAnnounce);
      });
    });
  }

  // 赛事规则
  getRules(obj) {
    return new Promise(resolve => {
      this.getRule(obj).subscribe(res => {
        if (res.result === 0 && res.data.constitution) {
          this.eventRule = res.data.constitution;
        } else {
          this.eventRule = {mark: '无'};
        }
        resolve(this.eventRule);
      });
    });
  }

  // 获取地区数据
  getProvinces() {
    const url = API.PRO_CITY_URL + '?langType=zh_CN';
    return this.httpService.get(url).map((rs) => rs.json());
  };

  get getSwiperData() {
    return this._swiper.asObservable();
  }

  getSwiperPicture() {
    this.getSwiper().subscribe(res => {
      if (res.result === 0 && res.data.list.length > 0) {
        this.eventSwiper = res.data.list;
        this._swiper.next(this.eventSwiper);
      }
    });
  };

  /**
   * @description 查詢賽事赛事详情基本信息
   * @author ouyqx-691
   * @param  matchId 赛事ID
   */
  getCompetitionBasicInfo(matchId: number) {
    const url = API.COMPETITION_BASIC_INFO_URL + '?matchId=' + matchId;
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 查詢赛事详情详情信息
   * @author ouyqx-691
   * @param  matchId 赛事ID
   */
  getCompetitionInfo(matchId: number) {
    const url = API.COMPETITION_INFO_URL + '?matchId=' + matchId;
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 查詢赛事详情（淘汰赛、积分）赛程列表
   * @author ouyqx-691
   * @param  matchId
   */
  getCompetitionSchedule(params) {
    const url = API.COMPETITION_SCHEDULE_URL + '?' + this.toolsService.param(params);
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 获取杯赛赛程
   * @author ouyqx-691
   * @date 2017/10/12
   * @param userId:用戶id
   */
  getCupCompetitionSchedule(params) {
    const url = API.CUP_MATCH_SCHEDULE_URL + '?' + this.toolsService.param(params);
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 查詢赛事详情公告列表
   * @author ouyqx-691
   * @param  params
   */
  getCompetitionNotice(params) {
    const url = API.COMPETITION_NOTICE_URL + '?' + this.toolsService.param(params);
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 查詢赛事详情排名列表
   * @author ouyqx-691
   * @param  params
   */
  getCompetitionRanking(params) {
    const url = API.COMPETITION_RANKING_INFO_URL + '?' + this.toolsService.param(params);
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 查詢賽事赛事详情章程信息
   * @author ouyqx-691
   * @param  matchId 赛事ID
   */
  getCompetitionConstitution(matchId: number) {
    const url = API.COMPETITION_CON_URL + '?matchId=' + matchId;
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 获取赛事排名详细信息
   * @author ouyqx-691
   * @date 2017/10/09
   * @param  params{id:排名id，matchType:球类类型}
   */
  getRankingDetail(params) {
    const url = API.COMPETITION_RANKING_DETAIL_URL + '?' + this.toolsService.param(params);
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 获取用户信息
   * @author ouyqx-691
   * @date 2017/10/10
   * @param userId:用戶id
   */
  getUserInfo(userId: string) {
    const url = API.USER_INFO_URL + '?userId=' + userId;
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 验证进入管理页面
   * @author lihao-1157
   * @date 2017/11/9
   * @param matchId:赛事id
   */
  getManagerValidate(matchId: number) {
    const url = API.COMPETITION_MANAGERVALIDATE_URL + '?matchId=' + matchId;
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 补录团体参赛人员
   * @author lihao-1157
   * @date 2017/11/10
   * @param params
   */
  reAddMatchTeam(params) {
    const url = API.COMPETITION_READDMATCHTEAM_URL;
    return this.httpService.postUrlencodeStr(url, params).map((res) => res.json());
  }

  /**
   * @description 删除团体参赛人员
   * @author lihao-1157
   * @date 2017/11/10
   * @param params
   */
  deleteMatchTeam(params) {
    const url = API.COMPETITION_MATCHTEAMDELETE_URL + '?' + this.toolsService.param(params);
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 获取团体参赛人员
   * @author lihao-1157
   * @date 2017/11/10
   * @param params
   */
  getTeamUserList(params): Observable<SNSResult<CommonPageVo<MatchIpSignTeamResp>>> {
    const url = API.COMPETITION_TEAMUSERLIST_URL + '?' + this.toolsService.param(params);
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 获取赛事表单自定义字段
   * @author lihao-1157
   * @date 2017/11/10
   * @param params
   */
  getMatchSignField(params): Observable<SNSResult<MatchSignFieldResp>> {
    const url = API.COMPETITION_MATCHSIGNFIELD_URL + '?' + this.toolsService.param(params);
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 获取赛事配置
   * @author lihao-1157
   * @date 2017/12/1,
   * @typeList 运动类型集合
   * @rankingDetail 排名详情数据字段展示集合
   */
  getMatchConfig() {
    const matchConfig = [{
      title: '足球',
      typeList: [{
        type: 3001,
        isTeam: false
      }],
      rankingDetail: {
        defaultList: [{
          title: '场次',
          key: 'countAll'
        }, {
          title: '进',
          key: 'goalIn'
        }, {
          title: '失',
          key: 'goalLost'
        }, {
          title: '胜',
          key: 'countWin'
        }, {
          title: '平',
          key: 'countTie'
        }, {
          title: '负',
          key: 'countLost'
        }, {
          title: '净胜',
          key: 'goalDifference'
        }, {
          title: '积分',
          key: 'point'
        }]
      }
    }, {
      title: '篮球',
      typeList: [{
        type: 3002,
        isTeam: false
      }],
      rankingDetail: {
        defaultList: [{
          title: '得分',
          key: 'pointAvgWin'
        }, {
          title: '失分',
          key: 'pointAvgLost'
        }, {
          title: '分差',
          key: 'pointAvgDifference'
        }, {
          title: '胜',
          key: 'countWin'
        }, {
          title: '负',
          key: 'countLost'
        }, {
          title: '胜率',
          key: 'winningPercentage',
          symbol: '%'
        }, {
          title: '连胜',
          key: 'consecutiveWin'
        }]
      }
    }, {
      title: '羽毛球',
      typeList: [{
        type: 3003,
        isTeam: false
      }, {
        type: 300301,
        isTeam: true
      }],
      rankingDetail: {
        teamList: [{
          title: '胜场',
          key: 'sceneWin'
        }, {
          title: '负场',
          key: 'sceneLost'
        }, {
          title: '净胜场',
          key: 'sceneNet'
        }, {
          title: '得分',
          key: 'scoreWin'
        }, {
          title: '失分',
          key: 'scoreLost'
        }, {
          title: '净胜分',
          key: 'scoreNet'
        }],
        defaultList: [{
          title: '胜局',
          key: 'countWin'
        }, {
          title: '负局',
          key: 'countLost'
        }, {
          title: '净胜局',
          key: 'countNet'
        }, {
          title: '胜',
          key: 'totalWin'
        }, {
          title: '负',
          key: 'totalLost'
        }, {
          title: '积分',
          key: 'point'
        }]
      }
    }, {
      title: '网球',
      typeList: [{
        type: 3004,
        isTeam: false
      }, {
        type: 300401,
        isTeam: true
      }],
      rankingDetail: {
        teamList: [{
          title: '胜场',
          key: 'sceneWin'
        }, {
          title: '负场',
          key: 'sceneLost'
        }, {
          title: '净胜场',
          key: 'sceneNet'
        }, {
          title: '胜局',
          key: 'countWin'
        }, {
          title: '负局',
          key: 'countLost'
        }, {
          title: '净胜局',
          key: 'countNet'
        }],
        defaultList: [{
          title: '胜盘',
          key: 'roundWin'
        }, {
          title: '负盘',
          key: 'roundLost'
        }, {
          title: '净胜盘',
          key: 'roundNet'
        }, {
          title: '胜',
          key: 'totalWin'
        }, {
          title: '负',
          key: 'totalLost'
        }, {
          title: '积分',
          key: 'point'
        }]
      }
    }, {
      title: '乒乓球',
      typeList: [{
        type: 3005,
        isTeam: false
      }, {
        type: 300501,
        isTeam: true
      }],
      rankingDetail: {
        teamList: [{
          title: '胜场',
          key: 'sceneWin'
        }, {
          title: '负场',
          key: 'sceneLost'
        }, {
          title: '净胜场',
          key: 'sceneNet'
        }, {
          title: '得分',
          key: 'scoreWin'
        }, {
          title: '失分',
          key: 'scoreLost'
        }, {
          title: '净胜分',
          key: 'scoreNet'
        }],
        defaultList: [{
          title: '胜局',
          key: 'countWin'
        }, {
          title: '负局',
          key: 'countLost'
        }, {
          title: '净胜局',
          key: 'countNet'
        }, {
          title: '胜',
          key: 'totalWin'
        }, {
          title: '负',
          key: 'totalLost'
        }, {
          title: '积分',
          key: 'point'
        }]
      }
    }];

    return matchConfig;
  }

  /**
   * @description 网羽乒比分查看(个人)
   * @author lihao-1157
   * @param  matchScheduleId
   */
  getAloneMultilayerScoreScan(matchScheduleId): Observable<SNSResult<MultilayerScoreVOAlone>> {
    const url = API.COMPETITION_GETALONEMULTILAYERSCORESCAN_URL + '?matchScheduleId=' + matchScheduleId;
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 网羽乒比分查看(团体)
   * @author lihao-1157
   * @param  matchScheduleId
   */
  getMultilayerScoreScan(matchScheduleId): Observable<SNSResult<MultilayerScoreVO>> {
    const url = API.COMPETITION_GETMULTILAYERSCORESCAN_URL + '?matchScheduleId=' + matchScheduleId;
    return this.httpService.get(url).map((res) => res.json());
  }
}








